package handles

import (
	"fmt"
	"hawkeye/common/logger"
	"hawkeye/common/storage"
	"hawkeye/event"
	"hawkeye/protocol"
	"hawkeye/server/model"
	"strings"
	"sync"

	"github.com/panjf2000/gnet/v2"
)

// RegisterHandler 注册处理器
type RegisterHandler struct {
	BaseHandler
	dataType protocol.RegisterData
}

// NewRegisterHandler 创建注册处理器
func NewRegisterHandler(connMutex *sync.RWMutex, connections map[gnet.Conn]string) *RegisterHandler {
	return &RegisterHandler{
		BaseHandler: BaseHandler{
			connMutex:   connMutex,
			connections: connections,
		},
	}
}

// Handle 处理注册事件
func (h *RegisterHandler) Handle(ctx *event.Context, data interface{}) error {
	registerData, err := protocol.Convert(data, h.dataType)
	if err != nil {
		return fmt.Errorf("invalid data format: %v", err)
	}

	// 注册逻辑处理
	connIp := strings.Split(ctx.ConnID, ":")[0]
	// 将注册数据保存到数据库
	var agent model.Agent

	storage.GDB.Select("*").Find(&agent, "conn_ip = ?", connIp)

	// 如果数据库中没有找到对应的agent，则创建一个新的agent
	if agent.ID == 0 {
		agent = model.Agent{
			ConnIP:    connIp,
			HostName:  registerData.HostName,
			HostIP:    registerData.HostIP,
			OSType:    registerData.OsType,
			OSArch:    registerData.OSArch,
			OSVersion: registerData.OSVersion,
		}
		storage.GDB.Create(&agent)
	} else {
		// 如果数据库中找到对应的agent，则更新agent的信息
		agent.HostName = registerData.HostName
		agent.HostIP = registerData.HostIP
		agent.OSType = registerData.OsType
		agent.OSArch = registerData.OSArch
		agent.OSVersion = registerData.OSVersion
		storage.GDB.Save(&agent)
	}
	logger.Info("agent: ", agent)
	return nil
}
